﻿#include "base/Utils.h"

#if defined(WIN32)
#include <windows.h>
#include<time.h> 
#include <iostream>


//CPU利用率  
FILETIME m_preidleTime;
FILETIME m_prekernelTime;
FILETIME m_preuserTime;


__int64 CompareFileTime2(FILETIME time1, FILETIME time2)
{
	__int64 a = time1.dwHighDateTime << 32 | time1.dwLowDateTime;
	__int64 b = time2.dwHighDateTime << 32 | time2.dwLowDateTime;


	return   b - a;
}


double CpuUseage()
{
	FILETIME idleTime;
	FILETIME kernelTime;
	FILETIME userTime;
	GetSystemTimes(&idleTime, &kernelTime, &userTime);


	__int64 idle = CompareFileTime2(m_preidleTime, idleTime);
	__int64 kernel = CompareFileTime2(m_prekernelTime, kernelTime);
	__int64 user = CompareFileTime2(m_preuserTime, userTime);


	if (kernel + user == 0)
		return 0.0;
	//（总的时间-空闲时间）/总的时间=占用cpu的时间就是使用率  
	double cpu = abs((kernel + user - idle) * 100 / (kernel + user));

	__int64 cpu2 = (kernel + user - idle) * 100 / (kernel + user);

	std::cout << "CPU利用率:" << cpu2 << "%" << std::endl;

	m_preidleTime = idleTime;
	m_prekernelTime = kernelTime;
	m_preuserTime = userTime;
	return cpu;
}
#endif